/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hazardsource.domain.HazardSource;
import com.koron.hazardsource.domain.StandardRisk;
import com.koron.hazardsource.mapper.HazardSourceMapper;
import com.koron.hazardsource.mapper.StandardRiskMapper;
import com.koron.hazardsource.service.impl.HazardSourceServiceImpl;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.hazardsource.util.Immutable;
import com.koron.risk.domain.LocalHazardSource;
import com.koron.risk.mapper.LocalHazardSourceMapper;
import com.koron.risk.service.api.PrivateHazardSourceService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@PropertySource({ "classpath:flow.properties" })
public class PrivateHazardSourceServiceImpl implements PrivateHazardSourceService,AfterApprovalService,InitializingBean {

	private final static Logger logger= LoggerFactory.getLogger(PrivateHazardSourceServiceImpl.class);
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void afterPropertiesSet() throws Exception {
		Map map = flowManagement.getHandlers();
		map.put("PrivateHazardSource", this);
	}

	@Autowired
	private HazardSourceServiceImpl hazardSourceService;

	@Autowired
	private LocalHazardSourceApprovalServiceImpl service;

	@Autowired
	private FlowManagement flowManagement;

	@Value("${lhs_flow_template_key}")
	private String templateKey;
	@Value("${flow.standard.setCode}")
	private String safeStandSetCode;

	@SuppressWarnings({ "unchecked" })
	@Override
	public MessageBean<?> merge(StaffBean user, List<HazardSource> hsList, String title, String note ) {
		MessageBean<?> msg = hazardSourceService.saveSourceAndRiskDraft(hsList, user);
		try {
			List<String> idList = new ArrayList<String>();
			if(msg.getData() != null){
				idList = (List<String>) msg.getData();
			}else{
				return msg;
			}
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
			audit.setId(DefaultIdGenerator.getInstance().generateLongId());
			audit.setTitle(title);
			audit.setDescription(note);
			audit.setInitiatorCode(user.getCode());
			audit.setInitiatorAccount(user.getUserid());
			audit.setTarget("PrivateHazardSource");		//专属危险源归并
			audit.setOperation(1);
			audit.setTemplateKey(templateKey);
			audit.setState(1);
			audit.setFlowType(1);
			audit.setSetCode(safeStandSetCode);
			audit.setFlowName(Immutable.ADD_STD_HAZARD_SOURCE);
			audit.setBusinessIds(new Gson().toJson(idList));
			if(!flowManagement.initFlow(user, audit, new HashMap<>())){
				hazardSourceService.delete(idList);
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
				return msg;
			}
			hazardSourceService.updateFstatusflag(idList, 1);
			List<String> lhsIdList = new ArrayList<String>();
			for (HazardSource hs : hsList) {
				String lhsIdStr = hs.getDerivationids();
				if(StringUtils.isEmpty(lhsIdStr)){
					continue;
				}
				String[] idArrat = lhsIdStr.split(",");
				for (String id : idArrat) {
					lhsIdList.add(id);
				}
			}
			service.updateDisposalState(lhsIdList, 1);  //处理中
		} catch (Exception e) {
			return msg;
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void editApproval(Audit audit) {
		List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
		try(SessionFactory factory=new SessionFactory();){
			HazardSourceMapper sourceMapper=factory.getMapper(HazardSourceMapper.class);
			StandardRiskMapper riskMapper=factory.getMapper(StandardRiskMapper.class);
			List<HazardSource> list = sourceMapper.queryByIdList("hazard_source_history", idList);
			for (HazardSource hazardSource : list) {
				hazardSource.setState(1);
				hazardSource.setFstatusflag(2);
				List<StandardRisk> tempList = riskMapper.queryByHazrdSourceId("tbl_risk_history", hazardSource.getId(), null, null);
				hazardSource.setRisks(tempList);
			}
			//保存危险源
			List<String> hsIdList = hazardSourceService.saveSourceAndRisk(list);
			hazardSourceService.updateFstatusflag(idList, 2);
			for (String hsId : hsIdList) {
				HazardSource hs = hazardSourceService.queryOneById("hazard_source", hsId);
				if(hs == null){
					continue;
				}
				String derivationids = hs.getDerivationids();
				String[] lhsIdArray = derivationids.split(",");
				for (String lhsId : lhsIdArray) {
					LocalHazardSourceMapper lhsMapper = factory.getMapper(LocalHazardSourceMapper.class);
					LocalHazardSource lhs = lhsMapper.getDetails("local_hazard_source", lhsId);
					if(lhs == null){
						continue;
					}
					lhs.setTemplateCode(hs.getCode());
					lhs.setDisposalState(2); //已做合并处理
					lhsMapper.update("local_hazard_source", lhs);
				}
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
	}

	@Override
	public void discardApproval(Audit audit) {
		// TODO Auto-generated method stub

	}

	@Override
	public void processDiscard(Audit audit) {
		// TODO Auto-generated method stub

	}



	@Override
	public void reject(Audit audit, List<String> userIdList) {
		// TODO 流程驳回操作
	}

	@Override
	public void passApproval(Integer operation, Audit audit) {
		// TODO 流程提交成功操作
	}
}
